package com.fly.demo;

import java.net.InetAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import javax.servlet.ServletContext;

import org.apache.commons.lang3.SystemUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.concurrent.CustomizableThreadFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import com.alibaba.druid.pool.DruidDataSource;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * Spring在启动完成后执行方法
 * 
 * @author 00fly
 * @version [版本号, 2018年7月31日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Slf4j
@Component
public class Startup implements ApplicationListener<ContextRefreshedEvent>
{
    @Autowired
    DruidDataSource dataSource;
    
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    RestTemplate restTemplate = new RestTemplate();
    
    /**
     * 事件回调
     * 
     * @param event
     */
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event)
    {
        ApplicationContext applicationContext = event.getApplicationContext();
        log.info("★★★★★★★★ {}", applicationContext);
        log.info("★★★★ JDBC_URL: {}", dataSource.getRawJdbcUrl());
        
        // servlet context初始化完成
        if (applicationContext.getParent() != null && SystemUtils.IS_OS_WINDOWS)
        {
            try
            {
                ServletContext servletContext = applicationContext.getBean(ServletContext.class);
                String contextPath = servletContext.getContextPath();
                // ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
                ExecutorService cachedThreadPool = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(), new CustomizableThreadFactory("cache-pool-"));
                for (int i = 8080; i < 8090; i++)
                {
                    int port = i;
                    cachedThreadPool.execute(() -> openBrowser(contextPath, port));
                }
            }
            catch (Exception e)
            {
                log.error(e.getMessage(), e);
            }
        }
    }
    
    private void openBrowser(String contextPath, int port)
    {
        try
        {
            String ip = InetAddress.getLocalHost().getHostAddress();
            String url = "http://" + ip + ":" + port + contextPath;
            ResponseEntity<String> responseEntity = restTemplate.getForEntity(url + "/doc.html", String.class);
            if (responseEntity.getStatusCode() == HttpStatus.OK)
            {
                log.info("now open Browser...");
                Runtime.getRuntime().exec("cmd /c start /min " + url + "/user/");
                Runtime.getRuntime().exec("cmd /c start /min " + url + "/doc.html");
                Runtime.getRuntime().exec("cmd /c start /min " + url + "/h2-console/");
            }
        }
        catch (Exception e)
        {
        }
    }
}
